package com.house.controller;

import cn.hutool.core.bean.BeanUtil;
import com.house.dto.UserDTO;
import com.house.entity.User;
import com.house.service.UserSerivce;
import com.house.utils.Code;
import com.house.utils.Constant;
import com.house.utils.JWTUtils;
import com.house.utils.Result;
import com.house.vo.UserVO;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Consumer;

/**
 * @version 1.0
 * @Author OhygC
 * @since 1.0
 */
@Api(value = "注册登录，用户管理模块，房东管理模块" ,tags = "注册登录，用户管理模块，房东管理模块相关接口")
@Validated
@RestController
@RequestMapping("/user")
@PropertySource(value = "classpath:default.properties",encoding = "UTF8")
public class UserController {
    /** 设置默认状态 */
    @Value("${state}")
    private Integer state;

    /** 设置默认角色*/
    @Value("${userRole}")
    private String userRole;
    @Resource
    private UserSerivce userSerivce;

    @ApiOperation(value = "注册接口",notes = "需要字段username,password,uname,phone,idcard")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "username",value = "用户名",dataType = "string",required = true),
            @ApiImplicitParam(name = "password",value = "密码",dataType = "string",required = true),
            @ApiImplicitParam(name = "uname",value = "姓名",dataType = "string",required = true),
            @ApiImplicitParam(name = "phone",value = "电话",dataType = "string",required = true),
            @ApiImplicitParam(name = "idcard",value = "身份证号",dataType = "string",required = true)
    })
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO){
        //判断参数是否为空
        if (userDTO.getPhone() == null || "".equals(userDTO.getPhone().trim())){
            return new Result(Code.PARAMETER_ERR,"电话为空");
        }
        //判断用户是否注册
        User user = userSerivce.selectUserByPhone(userDTO.getPhone());
        if (user == null){
            //设置注册默认用户和状态
            userDTO.setState(state);
            userDTO.setUserRole(userRole);
            //注册用户
            userSerivce.register(userDTO);
            return new Result(Code.SAVE_OK,"注册成功");
        }
        return new Result(Code.PARAMETER_ERR,"用户已存在");
    }

    @ApiOperation(value = "登录接口",notes = "需要字段phone,password")
    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO){
        //判断电话密码是否为空
        if (userDTO.getPhone()==null ||"".equals(userDTO.getPhone().trim())){
            return new Result(Code.PARAMETER_ERR,"请输入手机号");
        }
        if (userDTO.getPassword()==null ||"".equals(userDTO.getPassword().trim())){
            return new Result(Code.PARAMETER_ERR,"请输入密码");
        }

        //判断数据库是否存在该账号
        User user = userSerivce.selectUserByPhone(userDTO.getPhone());
        if (user == null){
            return new Result(Code.PARAMETER_ERR,("手机号输入错误，或手机号未注册"));
        }

        //给传入的密码进行加密并传给一个新对象
        User loginUser = userSerivce.login(userDTO);

        //拿到加密密码和数据库原密码
        String loginPassword = loginUser.getPassword();
        String userPassword = user.getPassword();

        //判断密码是否相同
        if (!loginPassword.equals(userPassword)){
            return new Result(Code.LOGIN_ERR,"登录失败，密码错误");
        }

        //获取存在用户的id和状态
        Integer id = user.getId();
        String state = String.valueOf(user.getState());

        //定义一个map，将前端所需要数据传给前端
        Map<String,String> map=new HashMap<>();
        map.put("id", String.valueOf(id));
        map.put("username",user.getUsername());
        map.put("uname",user.getUname());
        map.put("phone",user.getPhone());
        map.put("idcard", user.getIdcard());
        map.put("userRole",user.getUserRole());
        map.put("state",state);

        //使用JWT工具类得到token
        String token = JWTUtils.getToken(map);
        map.put("token",token);
        return new Result(Code.LOGIN_OK,map,"登录成功");
    }

    @ApiOperation(value = "修改用户名和密码",notes = "需要字段id，username，password")
    @PostMapping("/updateUsername")
    public Result updateUser(@RequestBody User user){
        //判断是否选择用户
        if (user.getId() == null){
            return new Result(Code.UPDATE_ERR,"请选择需要修改的用户");
        }

        //根据id查询该用户
        User userById = userSerivce.findUserById(user.getId());
        if (userById == null){
            return new Result(Code.GET_ERR,"未查询到该用户");
        }

        //判断用户名和密码是否输入
        if (user.getUsername() == null || "".equals(user.getUsername().trim())){
            return new Result(Code.PARAMETER_ERR,"用户名未输入");
        }
        if (user.getPassword() == null || "".equals(user.getPassword().trim())){
            return new Result(Code.PARAMETER_ERR,"密码未输入");
        }
        //如果执行了修改操作，会返回1
        int count = userSerivce.updateUser(user);
        if (count!=1){
            return new Result(Code.SYSTEM_ERR,"系统异常，请联系管理员！");
        }
        return new Result(Code.UPDATE_OK,"修改成功");
    }

    @ApiOperation(value = "查询所有用户",notes = "需要字段userRole")
    @PostMapping("findUsers")
    public Result findUsers(@RequestBody Map<String,Object> params){
        //定义一个map，将查到的数据返回给前端
        Map<String, Object> map = new HashMap<>(4);

        //获取登录时传过来的角色
        String role = (String) params.get("userRole");

        //查询用户总数
        int usersTotal = userSerivce.findUsersTotal(role);

        //判断角色是否为空且角色是否为普通用户
        //如果为普通用户就查询普通用户
        if ( role !=null || role.equals(Constant.USER_ROLE)){
            if (usersTotal != 0){
                Page<Map<String, Object>> users1 = userSerivce.findUsers(params);
                List<Map<String, Object>> users = users1.getContent();
                List<UserVO> list = BeanUtil.copyToList(users, UserVO.class);
                map.put("list",list);
                map.put("totalPages",users1.getTotalPages());
                map.put("totalElements",users1.getTotalElements());
                return new Result(Code.UPDATE_OK,map,"查询成功");
            }
        }
        //如果不为普通用户就执行查询所有房东
        if (usersTotal != 0){
            Page<Map<String, Object>> users1 = userSerivce.findUsers(params);
            List<Map<String, Object>> users = users1.getContent();
            List<UserVO> list = BeanUtil.copyToList(users, UserVO.class);
            map.put("list",list);
            map.put("totalPages",users1.getTotalPages());
            map.put("totalElements",users1.getTotalElements());
            return new Result(Code.UPDATE_OK,map,"查询成功");
        }
        return new Result(Code.UPDATE_ERR,map,"查询失败");
    }

    @ApiOperation(value = "提交审核接口，用于修改审核状态",notes = "只需要传id，state即可")
    @PostMapping("submit")
    public Result submit(@RequestBody User user){
        //判断普通用户是否提交审核
        if (user.getState() == Constant.DEFUALT_VALUE){
            return new Result(Code.UPDATE_OK,"已提交审核，请等待");
        }

        int count = userSerivce.updateState(user.getId());
        if (count !=Constant.DEFUALT_VALUE){
            return new Result(Code.SYSTEM_ERR,"系统错误，请联系管理员");
        }
        return new Result(Code.UPDATE_OK,"提交成功,正在审核");
    }

    @ApiOperation(value = "查询待审核用户",notes = "只需要传state即可,需要将state=1")
    @PostMapping("toBeReviewed")
    public Result toBeReviewed(@RequestBody Map<String,Object> params){
        Map<String, Object> map = new HashMap<>(4);

        //获取传入参数state
        String state = (String) params.get("state");

        //根据待审核状态查询所有待审核用户
        int usersTotal = userSerivce.findUsersTotal(state);
        map.put("userTotal", usersTotal);
        if (usersTotal != 0){
            //查找状态为1的所有用户
            Page<Map<String, Object>> user=userSerivce.findUsersByState(params);
            List<Map<String, Object>> content = user.getContent();
            long totalElements = user.getTotalElements();
            int totalPages = user.getTotalPages();
            List<UserVO> list = BeanUtil.copyToList(content, UserVO.class);
            map.put("list",list);
            map.put("totalElements",totalElements);
            map.put("totalPages",totalPages);
            return new Result(Code.UPDATE_OK,map,"查询成功");
        }
        return new Result(Code.UPDATE_ERR,map,"没有需要审核的用户");
    }

    @ApiOperation(value = "同意待审核用户",notes = "需要传指定用户id，和state状态码,state状态码为1")
    @PostMapping("consentAudit")
    public Result consentAudit(@RequestBody Map<String,Integer> params){
        Integer state = params.get("state");
        if (state != 1){
            return new Result(Code.SYSTEM_ERR,"待审核有误，请联系技术人员修复");
        }

        //后台通过审核
        int count = userSerivce.updateState1(params);
        if (count != Constant.DEFUALT_VALUE){
            return new Result(Code.SYSTEM_ERR,"系统错误，请联系技术人员修复");
        }
        return new Result(Code.UPDATE_OK,"修改成功");
    }

    @ApiOperation(value = "模糊查询名字",notes = "需要传name")
    @PostMapping("findUsersByName")
    public Result findUsersByName(@RequestBody UserDTO userDTO){
        Map<String, Object> map = new HashMap<>(4);

        if (userDTO.getUname() == null || "".equals(userDTO.getUname())){
            return new Result(Code.PARAMETER_ERR,"请输入姓名");
        }
        //根据名字分页模糊查询
        Page<User> usersByName = userSerivce.findUsersByName(userDTO);
        List<User> content = usersByName.getContent();
        int totalPages = usersByName.getTotalPages();
        long totalElements = usersByName.getTotalElements();
        List<UserVO> list = BeanUtil.copyToList(content, UserVO.class);
        map.put("content",list);
        map.put("totalPages",totalPages);
        map.put("totalElements",totalElements);
        if (content.contains("")|| content.isEmpty()){
            return new Result(Code.GET_ERR,"未查到该用户");
        }
        return new Result(Code.GET_OK,map,"查询成功");
    }

    @ApiOperation(value = "查询个人信息")
    @PostMapping("findUserById")
    public Result findUserById(@RequestBody User user){
        Map<String,Object> map =new HashMap<>();
        Optional<User> oneUserById = userSerivce.findOneUserById(user.getId());
        map.put("oneUserById",oneUserById);
        return new Result(Code.GET_OK,map,"查询成功");
    }
}
